/**
 * 缓存工具类
 * 提供localStorage和sessionStorage的封装
 */

// 默认缓存期限（7天）
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7;

/**
 * 创建缓存对象
 */
function createCache(storage: Storage) {
  /**
   * 设置缓存
   * @param key 缓存键
   * @param value 缓存值
   * @param expire 过期时间（秒），默认7天
   */
  const setCache = (key: string, value: any, expire: number = DEFAULT_CACHE_TIME) => {
    const data = {
      value,
      expire: expire !== null ? new Date().getTime() + expire * 1000 : null,
    };
    storage.setItem(key, JSON.stringify(data));
  };

  /**
   * 获取缓存
   * @param key 缓存键
   * @returns 缓存值或null
   */
  const getCache = (key: string) => {
    const item = storage.getItem(key);
    if (!item) return null;

    try {
      const data = JSON.parse(item);
      const { value, expire } = data;

      // 检查是否过期
      if (expire === null || expire >= new Date().getTime()) {
        return value;
      }

      // 已过期，删除缓存
      removeCache(key);
      return null;
    } catch (error) {
      console.error('解析缓存数据失败:', error);
      removeCache(key);
      return null;
    }
  };

  /**
   * 删除缓存
   * @param key 缓存键
   */
  const removeCache = (key: string) => {
    storage.removeItem(key);
  };

  /**
   * 清空所有缓存
   */
  const clearCache = () => {
    storage.clear();
  };

  /**
   * 检查缓存是否存在
   * @param key 缓存键
   * @returns boolean
   */
  const hasCache = (key: string): boolean => {
    return getCache(key) !== null;
  };

  /**
   * 获取所有缓存键
   * @returns string[]
   */
  const getCacheKeys = (): string[] => {
    const keys: string[] = [];
    for (let i = 0; i < storage.length; i++) {
      const key = storage.key(i);
      if (key) keys.push(key);
    }
    return keys;
  };

  return {
    setCache,
    getCache,
    removeCache,
    clearCache,
    hasCache,
    getCacheKeys,
  };
}

// localStorage 缓存
const localCache = createCache(localStorage);

// sessionStorage 缓存
const sessionCache = createCache(sessionStorage);

// 导出常用方法（默认使用localStorage）
export const { setCache, getCache, removeCache, clearCache, hasCache, getCacheKeys } = localCache;

// 导出具体的缓存实例
export { localCache, sessionCache };

// 导出类型定义
export interface CacheData {
  value: any;
  expire: number | null;
}

/**
 * 缓存装饰器
 * @param key 缓存键
 * @param expire 过期时间（秒）
 */
export function cached(key: string, expire: number = DEFAULT_CACHE_TIME) {
  return function (target: any, propertyName: string, descriptor: PropertyDescriptor) {
    const method = descriptor.value;
    descriptor.value = async function (...args: any[]) {
      const cacheKey = `${key}_${JSON.stringify(args)}`;
      const cachedResult = getCache(cacheKey);
      
      if (cachedResult !== null) {
        return cachedResult;
      }
      
      const result = await method.apply(this, args);
      setCache(cacheKey, result, expire);
      return result;
    };
  };
}

/**
 * 用户相关缓存键常量
 */
export const CACHE_KEYS = {
  TOKEN: 'token',
  USER_INFO: 'userInfo',
  LANGUAGE: 'language',
  THEME: 'theme',
  SETTINGS: 'settings',
} as const;
